<template>
  <a-spin :spinning="confirmLoading" class="spin-style">
    <j-form-container :disabled="formDisabled"  style="width: 100%;">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row :gutter="24">
          <a-col :span="12">
            <a-row>
              <a-col>
                <a-form-model-item label="经度坐标" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="lng">
                  <a-input v-model="model.lng" placeholder="请输入经度坐标"></a-input>
                </a-form-model-item>
              </a-col>
              <a-col>
                <a-form-model-item label="纬度坐标" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="lat">
                  <a-input v-model="model.lat" placeholder="请输入纬度坐标"></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <label class="tip-label-style">*请点击地图上的位置，以获取道路信息，获取后可手动修改</label>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="路侧杆件ID" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="facilityId">
                  <a-input v-model="model.facilityId" placeholder="请输入路侧杆件ID"></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="运营商" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="manufacturerId">
                  <!-- <a-input v-model="model.manufacturerId" placeholder="请输入设备厂商"  ></a-input> -->
                  <j-dict-select-tag v-model="model.manufacturerId" title="请选择运营商" dictCode="road_equip_operators" placeholder="运营商"/>
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-row>
                  <a-col :span="24">
                    <a-form-model-item label="杆件位置" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="positionType">
                      <j-dict-select-tag v-model="model.positionType" title="请选择杆件位置" dictCode="position_type" placeholder="杆件位置" style="width: 40%"/>
                      <a-input v-model="model.positionMark" placeholder="请输入杆件号,如F杆"  style="width: 55%; margin-left: 5%;"></a-input>
                    </a-form-model-item>
                  </a-col>
                </a-row>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="示范区" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="zoneId">
                  <!-- <a-input v-model="model.zoneName" placeholder="请输入示范区"  ></a-input> -->
                  <j-dict-select-tag style="width: 100%;" v-model="model.zoneId" title="请选择示范区" dictCode="demonstration_zone" placeholder="请选择示范区"/>
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="所属地名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="locationName">
                  <a-input v-model="model.locationName" placeholder="请输入所属地名称"  ></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="所属地编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="locationId">
                  <a-input v-model="model.locationId" placeholder="请输入所属地编号"  ></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="应用场景" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="applyScene">
                  <j-dict-select-tag v-model="model.applyScene" title="请选择应用场景" dictCode="apply_scene" placeholder="请选择应用场景"/>
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="道路" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="roadId">
                  <a-select v-model="model.roadId" title="请选择道路" :options="roadOptions" @change="handleRoadChange" placeholder="请选择道路"/>
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="路口" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="crossId">
                  <a-select v-model="model.crossId" title="请选择路口" :options="crossOptions" @change="handleCrossChange" placeholder="请选择路口"/>
                </a-form-model-item>
              </a-col>
              <a-col v-if="uploadDisabled" :span="24">
                <a-form-model-item label="路侧杆件图片" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="fileList">
                   <a-upload
                      :action="uploadAction"
                      :multiple="true"
                      :headers="headers"
                      :file-list="fileList"
                      :disabled="fileUploadDisabled"
                      :showUploadList="showUploadList"
                      @change="handleChange"
                    >
                    <a-button> <a-icon type="upload" /> 上传图片 </a-button>
                  </a-upload>
                </a-form-model-item>
              </a-col>
              <a-col v-if="previewDisabled" :span="24">
                <a-form-model-item label="路侧杆件图片" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-col :span="8"
                    v-for="(item, index) in fileList" 
                    :key="item.id">
                        <a-card hoverable style="width: 100%; height: 100px;">
                          <img
                            slot="cover"
                            alt="example"
                            :src="item.url"
                            style="width: 100%; height: 100px;"
                          />
                        </a-card>
                  </a-col>
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="安装角度" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="installAngle">
                  <a-input v-model="model.installAngle" placeholder="请输入安装角度"  ></a-input>
                </a-form-model-item>
              </a-col>
              
            </a-row>
          </a-col>
          <a-col :span="12">
            <a-row>
              <div style="width: 600px; height: 750px">
                <!-- <div id="map_canvas" style="width: 500px; height: 500px"></div> -->
                <BMap :pageHeight="550" ref="map" :zoom="12" @update-lnglat="updateLnglat"></BMap>
              </div>
            </a-row>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
  </a-spin>
</template>

<script>
  import Vue from 'vue'
  import { ACCESS_TOKEN } from "@/store/mutation-types"
  import { getFileAccessHttpUrl } from '@/api/manage';
  import BMap from '@/views/components/map/index.vue'
  import JDictSelectTag from '@/components/dict/JDictSelectTag.vue'
  import { httpAction, getAction } from '@/api/manage'
  import { validateDuplicateValue } from '@/utils/util'
  import { getRoadList } from '@/api/basicinfo/road/road'
  import { getCrossList } from '@/api/basicinfo/road/cross'
import { install } from 'vuedraggable'
  const uidGenerator=()=>{
    return '-'+parseInt(Math.random()*10000+1,10);
  }

  export default {
    name: 'PoleForm',
    components: {
      BMap,
      JDictSelectTag
    },
    props: {
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      },
      showUpload: {
        type: Boolean,
        default: true,
        required: false
      },
      showPreview: {
        type: Boolean,
        default: false,
        required: false
      },
    },
    data () {
      return {
        model:{
          lng: null,
          lat: null,
          crossId: null,
          fileList: [],
        },
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        confirmLoading: false,
        validatorRules: {
           facilityId: [
              { required: true, message: '请输入设备序列号!'},
           ],
           manufacturerId: [
              { required: true, message: '请输入设备厂商!'},
           ],
           positionType: [
              { required: true, message: '请选择杆件位置!'},
           ],
          //  positionMark: [
          //     { required: true, message: '请输入杆件位置!'},
          //  ],
           locationName: [
              { required: true, message: '请输入所属地id!'},
           ],
           locationId: [
              { required: true, message: '请输入所属地id!'},
           ],
           applyScene: [
              { required: true, message: '请选择应用场景!'},
           ],
           zoneId: [
              { required: true, message: '请选择示范区!'},
           ],
           roadId: [
            { required: true, message: '请选择道路!'},
           ],
           crossId: [
            { required: true, message: '请选择路口!'},
           ],
          //  fileList: [
          //   { required: true, message: '请上传路侧杆件图片!'},
          //  ],
           installAngle: [
            { required: true, message: '请选择安装角度!'},
           ],
        },
        url: {
          add: "/basicinfo/roadside/pole/add",
          edit: "/basicinfo/roadside/pole/edit",
          queryById: "/basicinfo/roadside/pole/queryById"
        },
        crossOptions: [],
        roadOptions: [],
        crossList: [],
        currentRoadId: null,
        currentCrossId: null,
        markerImagePath: 'assets/icons/map/pole-red.png',
        markerImageWidth: 34,
        markerImageHeight: 40,
        uploadAction:window._CONFIG['domianURL']+"/sys/common/upload",
        headers:{},
        fileList: [],
        uploading: false,
        fileUploadDisabled: false,
        showUploadList: true,
      }
    },
    computed: {
      formDisabled(){
        return this.disabled
      },
      uploadDisabled(){
        return this.showUpload;
      },
      previewDisabled(){
        return this.showPreview;
      },
    },
    created () {
      const token = Vue.ls.get(ACCESS_TOKEN);
      this.headers = {"X-Access-Token":token};
      //备份model原始值
      this.modelDefault = JSON.parse(JSON.stringify(this.model));
      this.initRoadList();
      this.initCrossList();
    },
    methods: {
      add () {
        const that = this;
        // this.model = {
        //   lng: null,
        //   lat: null,
        //   crossId: null,
        //   fileList,
        // };
        this.edit(this.modelDefault);
        let point = new BMapGL.Point( this.$refs.map.mapCenter.lng, this.$refs.map.mapCenter.lat);
        this.$refs.map.map.centerAndZoom(point, this.$refs.map.zoom);
        this.$refs.map.onclickEventByAddMarker(that.markerImagePath, that.markerImageWidth, that.markerImageHeight, (e)=>{
          console.log(e);
        })
      },
      edit (record) {
        const that = this;
        this.model = Object.assign({}, record);
        console.log("this.model", this.model)
        if(this.model.fileList){
          console.log("this.model.fileList", this.model.fileList);
          // this.fileList = this.model.fileList;
          this.initFileList(this.model.fileList);
        }
        this.visible = true;
        // let point = new BMapGL.Point(record.lng, record.lat);
        // const item = {"name": record.facilityId, "sx": 0, "zy": 0, "scale":0.5, "color": "#000000", "bg": "point-pole"}
        // this.$refs.map.addMarker(point, item, record.id);
        const lnglat = {"lng": record.lng, "lat": record.lat};
        this.$refs.map.addImageMarker(lnglat, {iconPath: that.markerImagePath, width: that.markerImageWidth, height: that.markerImageHeight});
        this.$refs.map.map.centerAndZoom(lnglat, this.$refs.map.zoom);
        this.$refs.map.onclickEventByAddMarker(that.markerImagePath, that.markerImageWidth, that.markerImageHeight, (e)=>{
          console.log(e);
        })
      },
      submitForm () {
        const that = this;
        console.log('this.fileList: ',this.fileList);
        this.model.fileList = this.fileList;
        // 触发表单验证
        this.$refs.form.validate(valid => {
          if (valid) {
            that.confirmLoading = true;
            let httpurl = '';
            let method = '';
            if(!this.model.id){
              httpurl+=this.url.add;
              method = 'post';
            }else{
              httpurl+=this.url.edit;
               method = 'put';
            }

            httpAction(httpurl,this.model,method).then((res)=>{
              if(res.success){
                that.$message.success(res.message);
                that.$emit('ok');
              }else{
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.confirmLoading = false;
            })
          }
         
        })
      },
      //初始化道路字典
      initRoadList(){
        getRoadList().then((res)=>{
          if(res.success){
            this.roadOptions = res.result.map((item,index,arr)=>{
              let c = { label:item.roadName, value:item.id }
              return c;
            })
            // console.log('this.roadOptions: ',this.roadOptions)
          }
        });
      },
      //初始化路口字典
      initCrossList(){
        let param = {};
        this.queryCrossList(param);
      },
      queryCrossList(param){
                // 只有在路口变化时才清空poleId，初始化时不清空
        if(param && param.roadId) {
          this.model.crossId = null;
          this.crossOptions = [];
        }
        getCrossList(param).then((res)=>{
          if(res.success){
            this.crossList = res.result;
            this.crossOptions = res.result.map((item,index,arr)=>{
              let c = { label:item.name, value:item.id}
              return c;
            })
            console.log('this.crossOptions: ',this.crossOptions);
          }
        });
      },
      handleRoadChange(val){
        // console.log('val: ', val);
        for(let i = 0 ,length = this.roadOptions.length; i<length; i++){
          if(this.roadOptions[i].value === val) {
            this.model.roadName = this.roadOptions[i].label;
            break;
          }
        }
        if(this.currentRoadId !== val) {
          this.currentRoadId = val;
          this.queryCrossList({roadId: val});
        }
        console.log('this.roadOptions: ',this.roadOptions);
        console.log('this.crossOptions: ',this.crossOptions);
        console.log('this.model: ',this.model);
      },
      handleCrossChange(val){
        console.log('this.roadOptions: ',this.roadOptions);
        console.log('this.crossOptions: ',this.crossOptions);
        console.log('this.model: ',this.model);
        console.log('val: ', val);
        for(let i = 0 ,length = this.crossList.length; i<length; i++){
          if(this.crossList[i].id === val) {
            // this.model.crossId = val;
            this.model.crossName = this.crossList[i].name;
            // this.model.lng = this.crossList[i].lng;
            // this.model.lat = this.crossList[i].lat;
            // break;
          }
        } 
        console.log('this.crossOptions: ',this.crossOptions);
        console.log('this.model: ',this.model);
      },
      updateLnglat(latlng){
        console.log('latlng: ', latlng);
        // console.log('this: ', this);
        console.log('this.model: ', this.model);
        this.model.lng = latlng.lng;
        this.model.lat = latlng.lat;        
      },
      handleRemove(file) {
        const index = this.fileList.indexOf(file);
        const newFileList = this.fileList.slice();
        newFileList.splice(index, 1);
        this.fileList = newFileList;
      },
      handleChange(info) {
        console.log("--文件列表改变--")
        if(!info.file.status && this.uploadGoOn === false){
          info.fileList.pop();
        }
        let fileList = info.fileList
        if(info.file.status==='done'){
          if(this.number>0){
            fileList = fileList.slice(-this.number);
          }
          if(info.file.response.success){
            fileList = fileList.map((file) => {
              if (file.response) {
                let reUrl = file.response.message;
                file.url = getFileAccessHttpUrl(reUrl);
              }
              return file;
            });
          }
          //this.$message.success(`${info.file.name} 上传成功!`);
        }else if (info.file.status === 'error') {
          this.$message.error(`${info.file.name} 上传失败.`);
        }else if(info.file.status === 'removed'){
          this.handleDelete(info.file)
        }
        this.fileList = fileList
        if(info.file.status==='done' || info.file.status === 'removed'){
          //returnUrl为true时仅返回文件路径
          if(this.returnUrl){
            this.handlePathChange()
          }else{
            //returnUrl为false时返回文件名称、文件路径及文件大小
            this.newFileList = [];
            for(var a=0;a<fileList.length;a++){
              // update-begin-author:lvdandan date:20200603 for:【TESTA-514】【开源issue】多个文件同时上传时，控制台报错
              if(fileList[a].status === 'done' ) {
                var fileJson = {
                  fileName:fileList[a].name,
                  filePath:fileList[a].response.message,
                  fileSize:fileList[a].size
                };
                this.newFileList.push(fileJson);
              }else{
                return;
              }
              // update-end-author:lvdandan date:20200603 for:【TESTA-514】【开源issue】多个文件同时上传时，控制台报错
            }
            this.$emit('change', this.newFileList);
          }
        }
      },
      handlePathChange(){
        let uploadFiles = this.fileList
        let path = ''
        if(!uploadFiles || uploadFiles.length==0){
          path = ''
        }
        let arr = [];

        for(var a=0;a<uploadFiles.length;a++){
          // update-begin-author:lvdandan date:20200603 for:【TESTA-514】【开源issue】多个文件同时上传时，控制台报错
          if(uploadFiles[a].status === 'done' ) {
            arr.push(uploadFiles[a].response.message)
          }else{
            return;
          }
          // update-end-author:lvdandan date:20200603 for:【TESTA-514】【开源issue】多个文件同时上传时，控制台报错
        }
        if(arr.length>0){
          path = arr.join(",")
        }
        this.$emit('change', path);
      },
      initFileList(paths){
        console.log('paths: ', paths);
        if(!paths || paths.length==0){
          //return [];
          // update-begin- --- author:os_chengtgen ------ date:20190729 ---- for:issues:326,Jupload组件初始化bug
          this.fileList = [];
          return;
          // update-end- --- author:os_chengtgen ------ date:20190729 ---- for:issues:326,Jupload组件初始化bug
        }
        let fileList = [];
        for(var a=0;a<paths.length;a++){
          let url = paths[a].url;
          fileList.push({
            uid:uidGenerator(),
            name: paths[a].name,
            status: 'done',
            url: url,
            response:{
              status:"history",
              message:paths[a]
            }
          })
        }
        this.fileList = fileList;
      },
      handleDelete(file){
        //如有需要新增 删除逻辑
        console.log(file)
      },
    }
  }
</script>
<style scoped>
  div.ant-modal, div.ant-modal-content {
      width: 1200px;
  }
  .spin-style{
      width: 1000px;
  }
  .tip-label-style{
    display: inline;
    width: 100%;
    text-align: center;
    font-size: 10px;
    color: red;
  }
  .area-select.medium{
    width: 100px;
  }
</style>